﻿using System;
using Ellanet.Annotations;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using Ellanet.Wrappers;

namespace Ellanet.ViewModels
{
    class CountDownWindowViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public event RequestViewCloseHandler RequestViewClose;

        private readonly int _startNumber;
        private readonly StaticCode.Activity _activity;
        private int _countdownNumber;

        public delegate void RequestViewCloseHandler();

        public int CountdownNumber
        {
            get { return _countdownNumber; }
            set
            {
                _countdownNumber = value;
                OnPropertyChanged();
            }
        }

        public CountDownWindowViewModel(int startNumber, StaticCode.Activity activity)
        {
            _startNumber = startNumber;
            _activity = activity;
            ThreadPool.QueueUserWorkItem(CountdownThread);
        }

        private void CountdownThread(object stateInfo)
        {
            if (_startNumber > 0)
            {
                SpeechWrapper.Say(String.Format("Your {0} will start in", _activity), true);

                for (int i = _startNumber; i > 0; i--)
                {
                    SpeechWrapper.SayAsync(i.ToString(), true);
                    CountdownNumber = i;
                    Thread.Sleep(1000);
                }
            }

            OnRequestViewClose();
        }

        protected void OnRequestViewClose()
        {
            RequestViewClose?.Invoke();
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
